<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>



<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>

<%@ page import="org.apache.commons.fileupload.FileItem" %>

<%@ page import="java.io.*" %>


<%@ page import="com.pptree.vo.*" %>

<%@ page import="com.pptree.service.impl.*" %>


<%
	request.setCharacterEncoding("UTF-8");
	String message = "";
	News news = new News();
	NewsServiceImpl newsService = new NewsServiceImpl();
	String path = request.getServletContext().getRealPath("upload");
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if(isMultipart){
		try {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> fileItemList = upload.parseRequest(request);
		for(int i=0;i < fileItemList.size();i++){
			FileItem item = fileItemList.get(i);
			if(item.isFormField() == true){ //普通表单数据
				String nameAttrValue = item.getFieldName();
				if("tid".equals(nameAttrValue)){
					String tid = item.getString();
					news.setTid(Integer.parseInt(tid));
				}
				else if("title".equals(nameAttrValue)){
					String title = item.getString("UTF-8");
					news.setTitle(title);
				}
				else if("author".equals(nameAttrValue)){
					String author = item.getString("UTF-8");
					news.setAuthor(author);
				}
				else if("summary".equals(nameAttrValue)){
					String summary = item.getString("UTF-8");
					news.setSummary(summary);
				}
				else if("content".equals(nameAttrValue)){
					String content = item.getString("UTF-8");
					news.setContent(content);
				}
			}
			else{
				//文件上传
				//获得客户端上传文件的完整路径
				String uploadFilePath = item.getName();
				if(uploadFilePath != null && !uploadFilePath.equals("")){
					File fullFile = new File(uploadFilePath);
					String fileName = fullFile.getName();
					item.write(new File(path,fileName));
					String picpath = "upload/" + fullFile.getName();
					news.setPicpath(picpath);
				}
			}
		}
	}
	catch(Exception ex){
		message = "上传文件失败，失败原因是" + ex.getMessage();
	}
	int result = newsService.addNews(news);
	if(result > 0){
		response.sendRedirect("newsList.jsp");
	}
	else{
		message = "发布新闻失败！";
		request.setAttribute("message", message);
		request.getRequestDispatcher("/admin/addNews.jsp").forward(request, response);
	}
}
	

%>